import 'package:flutter/material.dart';
import 'package:flutter_demo1/http/core/hi_error.dart';
import 'package:flutter_demo1/http/dao/login_dao.dart';
import 'package:flutter_demo1/navigator/hi_navigator.dart';
import 'package:flutter_demo1/util/string_util.dart';
import 'package:flutter_demo1/util/toast.dart';
import 'package:flutter_demo1/widget/app_bar.dart';
import 'package:flutter_demo1/widget/login_button.dart';
import 'package:flutter_demo1/widget/login_effect.dart';
import 'package:flutter_demo1/widget/login_input.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool protect = false;
  bool loginEnable = false;
  String? userName;
  String? password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(
        "密码登录",
        rightTitle: "注册",
        rightButtonClick: () {
          HiNavigator.getInstance().onJumpTo(RouteStatus.registration);
        },
      ),
      body: Container(
        child: ListView(
          children: [
            LoginEffect(protect: protect),
            LoginInput(
              "用户名",
              "请输入用户名",
              onChanged: (text) {
                userName = text;
                _checkInput();
              },
            ),
            LoginInput(
              "密码",
              "请输入密码",
              obscureText: true,
              lineStretch: true,
              onChanged: (text) {
                password = text;
                _checkInput();
              },
              focusChanged: (focus) {
                setState(() {
                  protect = focus;
                });
              },
            ),
            Padding(
              padding: EdgeInsets.only(left: 20, top: 20, right: 20),
              child: LoginButton("登录", enable: loginEnable, onPressed: _send),
            ),
          ],
        ),
      ),
    );
  }

  void _checkInput() {
    bool enable;
    if (isNotEmpty(userName) && isNotEmpty(password)) {
      enable = true;
    } else {
      enable = false;
    }
    setState(() {
      loginEnable = enable;
    });
  }

  void _send() async {
    try {
      var result = await LoginDao.login(userName!, password!);
      print("result:$result");
      showWarnToast("result:$result");
      HiNavigator.getInstance().onJumpTo(RouteStatus.home);
    } on NeedAuth catch (e) {
      print("NeedAuth:${e.toString()}");
      showWarnToast("NeedAuth:{$e.message}");
    } on NeedLogin catch (e) {
      print("NeedLogin:${e.toString()}");
      showWarnToast("NeedLogin:{$e.message}");
    } on Exception catch (e) {
      print("Exception:${e.toString()}");
    }
  }
}
